/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.fiap.dao;

import java.sql.*;

/**
 *
 * @author Fabianoss
 */
public class FabricaConexao {

    private final String HOST = "localhost";
    private final String PORT = "3306";
    private final String BANCO = "avaliacao1";
    private final String USER = "root";
    private final String PASSWORD = "root";
    private final String DRIVE = "com.mysql.jdbc.Driver";
    private static FabricaConexao INSTANCE = null;
    private static Connection connection = null;

    private FabricaConexao() {
    }

    public static FabricaConexao getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new FabricaConexao();
        }
        return INSTANCE;
    }

    public Connection getConnection() {
        
            try {
                if (connection == null || connection.isClosed()) {
                 Class.forName(this.DRIVE);
                 this.connection = DriverManager.getConnection("jdbc:mysql://" + this.HOST + ":" + this.PORT + "/" + this.BANCO, this.USER, this.PASSWORD);
                }
            } catch (SQLException e) {
                System.out.println("Problema ao obter conexao: " + e.getMessage());
                e.printStackTrace();
            } catch (ClassNotFoundException ex) {
                System.out.println("Problema com o drive de conexao: " + ex.getMessage());
                ex.printStackTrace();
            }
        
        return this.connection;
    }

    public void closeConnection(PreparedStatement pstmt,Statement stmt,ResultSet result) {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                System.out.println("\n>> Problema ao fechar Connection\n");
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                System.out.println("\n>> Problema ao PreparedStatement\n");
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                System.out.println("\n>> Problema ao fechar Statement\n");
                e.printStackTrace();
            }
        }
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                System.out.println("\n>> Problema ao fechar ResultSet\n");
                e.printStackTrace();
            }
        }
    }

}